package com.bigchun.seeland;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import bean.ContentDataBean;
import myapp.MyApp;
import myview.LoadingDialog;
import util.MyLog;
import util.PreferenceUtil;
import util.RequestManager;
import util.SystemStatusManager;

public class SelectLanguageActivity extends BaseActivity implements DialogInterface.OnCancelListener {


    private LinearLayout ll_reback;
    private LinearLayout ll_english;
    private LinearLayout ll_chinese;
    private ImageView img_english;
    private ImageView img_chinese;
    private Context context;
    private MyApp myapp;
    private String token;
    private String languageType = "0";//0为中文    1为英文
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;

    private LoadingDialog loadingDialog;
    private LinearLayout ll_japanese;
    private ImageView img_japanese;
    private ContentDataBean.DataBean textContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_selectlanguage);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        initView();
        initLin();


    }


    private void initView() {
        ll_reback = findViewById(R.id.ll_reback);
        ll_english = findViewById(R.id.ll_english);
        ll_chinese = findViewById(R.id.ll_chinese);
        ll_japanese = findViewById(R.id.ll_japanese);
        img_english = findViewById(R.id.img_english);
        img_chinese = findViewById(R.id.img_chinese);
        img_japanese = findViewById(R.id.img_japanese);
        TextView tv_title = findViewById(R.id.tv_title);
        TextView tv_en = findViewById(R.id.tv_en);
        TextView tv_zh = findViewById(R.id.tv_zh);
        TextView tv_japanese = findViewById(R.id.tv_japanese);
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setOnCancelListener(this);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        if (textContent != null) {
            tv_title.setText(textContent.getSelectlanguage());
            tv_en.setText(textContent.getEnglish());
            tv_zh.setText(textContent.getChinese());
            tv_japanese.setText(textContent.getJapanese());
        }

        String yuyan = PreferenceUtil.getString("language", "zh");
        if ("en".equals(yuyan)) {
            img_chinese.setImageResource(R.mipmap.icon_nocheck);
            img_japanese.setImageResource(R.mipmap.icon_nocheck);
            img_english.setImageResource(R.mipmap.icon_checkd);
        } else if ("zh".equals(yuyan)) {
            img_chinese.setImageResource(R.mipmap.icon_checkd);
            img_english.setImageResource(R.mipmap.icon_nocheck);
            img_japanese.setImageResource(R.mipmap.icon_nocheck);
        }else if ("ja".equals(yuyan)) {
            img_japanese.setImageResource(R.mipmap.icon_checkd);
            img_chinese.setImageResource(R.mipmap.icon_nocheck);
            img_english.setImageResource(R.mipmap.icon_nocheck);
        }
    }


    private void initLin() {
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ll_english.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                languageType = "1";
                loadingDialog.show();
                getContentData("cn");
//                changeLanuaData(languageType);

            }
        });
        ll_chinese.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                languageType = "0";
                loadingDialog.show();
                getContentData("zh");


            }
        });
        ll_japanese.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                languageType = "2";
                loadingDialog.show();
                getContentData("ja");


            }
        });
    }

    /**
     * 切换语言
     */
    private void changeLanuaData(String type) {

        String url = myapp.getWebConfig() + "/api/user/changelanguage";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("type", type);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    dismissSelectDialog();
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void dismissSelectDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 获取配置信息
     */
    private void getContentData(String string) {
//        String string = PreferenceUtil.getString("language", "zh");
        String url = myapp.getWebConfig() + "/api/index/apptran";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("lang", string);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject textData = jsonObject.getJSONObject("data");
//                    textData = new Gson().fromJson(data.toString(), new TypeToken<ContentDataBean.DataBean>() {
//                    }.getType());
                    msg.obj = textData;
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    JSONObject js = (JSONObject) msg.obj;
                    sharedPreferences.edit().putString("textData", js.toString()).commit();
                    changeLanuaData(languageType);
                    break;
                case 3:
                    if ("0".equals(languageType)) {
                        //0为中文
                        img_chinese.setImageResource(R.mipmap.icon_checkd);
                        img_english.setImageResource(R.mipmap.icon_nocheck);
                        //切换为中文
                        switchLanguage("zh");
                        Intent intent = new Intent(SelectLanguageActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                    } else if ("1".equals(languageType)) {
                        //1为英文
                        img_chinese.setImageResource(R.mipmap.icon_nocheck);
                        img_english.setImageResource(R.mipmap.icon_checkd);
                        //切换为英文
                        switchLanguage("en");
                        Intent intent = new Intent(SelectLanguageActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                    }else if ("2".equals(languageType)) {
                        //1为英文
                        img_chinese.setImageResource(R.mipmap.icon_nocheck);
                        img_english.setImageResource(R.mipmap.icon_nocheck);
                        img_japanese.setImageResource(R.mipmap.icon_checkd);
                        //切换为日文
                        switchLanguage("ja");
                        Intent intent = new Intent(SelectLanguageActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                    }


                    break;
                case 4:

                    break;
                case 11:
                    if (!islogin) {
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
    private boolean islogin = false;

    /**
     * 设置状态栏背景状态
     */
    public void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }


    @Override
    public void onCancel(DialogInterface dialog) {

    }
}
